<?php
include('_pre.php');
include('helper.php');


/**
 * 生成验证码
 * @param  array  $config
 * @return
 */
function create_verify_code(array $config) {
    $Verify = new \Think\Verify($config);
    return $Verify->entry();
}

/**
 * 检查验证码
 * @param  string $code
 * @param  int $verify_code_id
 * @return boolean
 */
function check_verify_code($code, $verify_code_id = '') {
    $Verify = new \Think\Verify();
    return $Verify->check($code, $verify_code_id);
}
/**
 * 格式化的文件大小
 * @param  int $bytes
 * @return string
 */
function bytes_format($bytes) {
    // 单位
    $unit = array(' B', ' KB', ' MB',
                  ' GB', ' TB', ' PB',
                  ' EB', ' ZB', ' YB');

    // bytes的对数
    $log_bytes = floor(log($bytes, 1024));
    return round($bytes / pow(1024, $log_bytes), 2) . $unit[$log_bytes];
}
/**
 * 得到操作系统信息
 * @return string
 */
function get_system() {
    $sys = $_SERVER['HTTP_USER_AGENT'];

    if (stripos($sys, "NT 6.1")) {
        $os = "Windows 7";
    } else if (stripos($sys, "NT 6.0")) {
        $os = "Windows Vista";
    }  else if (stripos($sys, "NT 5.1")) {
        $os = "Windows XP";
    } else if (stripos($sys, "NT 5.2")) {
        $os = "Windows Server 2003";
    } else if (stripos($sys, "NT 5")) {
        $os = "Windows 2000";
    } else if (stripos($sys, "NT 4.9")) {
        $os = "Windows ME";
    } else if (stripos($sys, "NT 4")) {
        $os = "Windows NT 4.0";
    } else if (stripos($sys, "98")) {
        $os = "Windows 98";
    } else if (stripos($sys, "95")) {
        $os = "Windows 95";
    } else if (stripos($sys, "Mac")) {
        $os = "Mac";
    } else if (stripos($sys, "Linux")) {
        $os = "Linux";
    } else if (stripos($sys, "Unix")) {
        $os = "Unix";
    } else if (stripos($sys, "FreeBSD")) {
        $os = "FreeBSD";
    } else if (stripos($sys, "SunOS")) {
        $os = "SunOS";
    } else if (stripos($sys, "BeOS")) {
        $os = "BeOS";
    } else if (stripos($sys, "OS/2")) {
        $os = "OS/2";
    } else if (stripos($sys, "PC")) {
        $os = "Macintosh";
    } else if(stripos($sys, "AIX")) {
        $os = "AIX";
    } else {
        $os = "未知操作系统";
    }

    return $os;
}

/**
 * 生成密码
 *
 * @param string $pwd
 *        	明文密码
 * @param string $salt
 *        	标识
 * @return array 二維数组：password => 密码密文, salt => 标识
 */
function password($pwd, $salt = NULL) {
	if (strlen ( $salt ) != 6) {
		$salt = salt ();
	}
	return array (
			'password' => md5 ( md5 ( $pwd ) . $salt ),
			'salt' => $salt 
	);
}

/**
 * 生成辅助标识，用于密码、唯一ID
 *
 * @return string
 */
function salt() {
	return substr ( md5 ( rand () . md5 ( md5 ( time () ) + uniqid () ) ), 0, 6 );
}

/**
 * 生成32位的唯一ID
 *
 * @param string $namespace
 *        	命名空间
 * @return string
 */
function genid($namespace = '') {
	if (! $namespace) {
		$namespace = microtime ( TRUE );
	}
	return md5 ( $namespace . uniqid ( NULL, TRUE ) . salt () );
}

/**
 * 将unix时间戳转成字符
 *
 * @param int $time
 *        	unix时间戳，默认为当前时间
 * @param string $format
 *        	格式。默认为 Y-m-d H:i:s
 * @return string
 */
function timeToStr($time = NULL, $format = NULL) {
	if (! $time) {
		$time = time ();
	}
	if (! $format) {
		$format = 'Y-m-d H:i:s';
	}
	return date ( $format, $time );
}

/**
 * 获取当前时间的字符串格式
 *
 * @return string
 */
function now() {
	return timeToStr ();
}

/**
 * 从unix时间戳获取时间部分
 *
 * @param int $time
 *        	unix时间戳，默认为当前时间
 * @return string
 */
function getTimeStr($time = NULL) {
	return timeToStr ( $time, 'H:i:s' );
}

/**
 * 从unix时间戳获取日期部分
 *
 * @param int $time
 *        	unix时间戳，默认为当前时间
 * @return string
 */
function getDateStr($time = NULL) {
	return timeToStr ( $time, 'Y-m-d' );
}

/**
 * 从unix时间戳获取日期，并使用中文“年月日”表示
 *
 * @param int $time
 *        	unix时间戳，默认为当前时间
 * @return string
 */
function getChineseDate($time = NULL) {
	return timeToStr ( $time, 'Y年m月d日' );
}

/**
 * 获取文字长度
 *
 * @param string $str        	
 * @return int
 */
function strLength($str) {
	return (function_exists ( 'mb_strlen' ) ? mb_strlen ( $str, 'UTF-8' ) : strlen ( $str ));
}

/**
 * 检查是否包含特殊字符
 * @param  string  $subject 需要检查的字符串
 * @return boolean          是否包含
 */
function hasSpecialChar($subject) {
    $pattern = "/^(([^\^\.<>%&',;=?$\"':#@!~\]\[{}\\/`\|])*)$/";
    if (preg_match($pattern, $subject)) {
        return false;
    }
    return true;
}

/**
 * 是否包含特殊字符
 * @param  string  $value 需要检查的值
 * @return boolean       是否不含特殊字符
 */
function isNotExistSpecialChar($value) {
   if (hasSpecialChar($value)) {
       return false;
   }
   return true;
}

/**
 * 删除目录或者文件
 * @param  string  $path
 * @param  boolean $is_del_dir
 * @return fixed
 */
function del_dir_or_file($path, $is_del_dir = FALSE) {
    $handle = opendir($path);
    if ($handle) {
        // $path为目录路径
        while (false !== ($item = readdir($handle))) {
            // 除去..目录和.目录
            if ($item != '.' && $item != '..') {
                if (is_dir("$path/$item")) {
                    // 递归删除目录
                    del_dir_or_file("$path/$item", $is_del_dir);
                } else {
                    // 删除文件
                    unlink("$path/$item");
                }
            }
        }
        closedir($handle);
        if ($is_del_dir) {
            // 删除目录
            return rmdir($path);
        }
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return false;
        }
    }
}

/**
 * 生成随机码
 * @param  int $length
 * @param  int $type
 * @return string
 */
function rand_code($length, $type) {
    $rand_factor = array("0123456789",
                        "abcdefghijklmnopqrstuvwxyz",
                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                        "~@#$%^&*(){}[]|");

    if (($type < 0 && $type != -1) || $type > 4) {
        $type = 0;
    }

    if (0 == $type) {
        array_pop($rand_factor);
        $rand_src = implode("", $rand_factor);
    } else if (-1 == $type) {
        $rand_src = implode("", $rand_factor);
    } else {
        $rand_src = $rand_factor[$type];
    }

    $code = '';
    $count = strlen($rand_src) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $rand_src[rand(0, $count)];
    }

    return $code;
}

/**
 *  创建目录
 *
 * @param     string  $spath  创建的文件夹
 * @return    bool
 */
if ( ! function_exists('CreateDir'))
{
    function CreateDir($spath)
    {
        if(!function_exists('SpCreateDir'))
        {echo C("YDCMS_INC").'inc_fun_funAdmin.php';die;
            require_once(C("YDCMS_INC").'inc_fun_funAdmin.php');
        }
        return SpCreateDir($spath);
    }
}

/**
 * 获取当前登录用户信息
 * @param type $name
 */
function getUser($name) {
    $account = I("session.current_account");
    if(empty($name)){
        return $account;
    }
    return isset($account[$name]) ? $account[$name] : NULL;
}

/**
 * 获取当前登录用户名
 * @return type
 */
function getUserName(){
    return getUser('username');
}

/**
 * 获取当前登录用户ID
 * @return type1
 */
function getUserId(){
    return getUser("id");
}





//获得是否推荐的表述
function IsCommendArchives($iscommend, $arcatts)
{
    $sn = '';
    foreach($arcatts as $k=>$v)
    {
        $attname = cn_substr($v['attname'], 2);
        $sn .= (preg_match("#".$v['att']."#", $iscommend) ? ' '.$attname : '');
    }
    $sn = trim($sn);
    if($sn=='') return '';
    else return "[<font color='red'>$sn</font>]";
}

//获得推荐的标题
function GetCommendTitle($title,$iscommend)
{
    /*if(preg_match('#c#i',$iscommend))
    {
        $title = "$title<font color='red'>(推荐)</font>";
    }*/
    return $title;
}

//检查图片是否存在
function CheckPic($picname)
{
    if($picname!="")
    {
        return $picname;
    }
    else
    {
        return "images/dfpic.gif";
    }
}

//判断内容是否生成HTML
function IsHtmlArchives($ismake)
{
    if($ismake==1)
    {
        return "已生成";
    }
    else if($ismake==0)
    {
        return "仅动态";
    }
    else
    {
        return "<font color='red'>未生成</font>";
    }
}


/**
 * 检查是否只包含_、小写字母
 * @param string $value    需要检查的值
 * @return boolean      是否有效的名称
 */
function isLower($value) {
   if (preg_match("/^[a-z_\-0-9]+$/", $value)) {
       return true;
   }
   return false;
}

/**
 * 根据语言标识获取语言title
 * @param type $nid
 */
function getLangTitle($nid) {
    if(empty($nid)){
        return "未知";
    }
    $where = array("nid" => $nid);
    $title = M("Language")->field("title")->where($where)->find();
    if(isArrayAndNotEmpty($title)){
        return $title['title'];
    }
    return "未知";
}

/**
 * 把文件打包成为zip
 * @param  array $files       需要打包在同一个zip中的文件的路径
 * @param  string $out_dir    zip的文件的输出目录
 * @param  [type] $des_name   zip文件的名称m
 * @return boolean            打包是否成功
 */
function zip($files, $file_path, $out_dir, $des_name) {
    $zip = new ZipArchive;

    // 创建文件夹
    mkdir($out_dir);
    // 打包操作
    $result = $zip->open($out_dir . '/' . $des_name, ZipArchive::CREATE);
    if (true !== $result) {
        return false;
    }

    foreach ($files as $file) {
        // 添加文件到zip包中
        $zip->addFile($file_path . '/' . $file,
                      str_replace('/', '', $file));
    }
    $zip->close();

    return true;
}

/**
 * 解压zip文件
 * @param  string $zip_file 需要解压的zip文件
 * @param  string $out_dir  解压文件的输出目录
 * @return boolean          解压是否成功
 */
function unzip($zip_file, $out_dir) {
    $zip = new ZipArchive();
    if (true !== $zip->open($zip_file)) {
        return false;
    }

    $zip->extractTo($out_dir);
    $zip->close();

    return true;
}


/**
 * 获得字段创建信息
 *
 * @access    public
 * @param     string  $dtype  字段类型
 * @param     string  $fieldname  字段名称
 * @param     string  $dfvalue  默认值
 * @param     string  $mxlen  最大字符长度
 * @return    array
 */
function GetFieldMake($dtype, $fieldname, $dfvalue, $mxlen)
{
    $fields = array();
    if($dtype == "int" || $dtype == "datetime")
    {
        if($dfvalue == "" || preg_match("#[^0-9-]#", $dfvalue))
        {
            $dfvalue = 0;
        }
        $fields[0] = " `$fieldname` int(11) NOT NULL default '$dfvalue';";
        $fields[1] = "int(11)";
    }
    else if($dtype == "stepselect")
    {
        if($dfvalue == "" || preg_match("#[^0-9\.-]#", $dfvalue))
        {
            $dfvalue = 0;
        }
        $fields[0] = " `$fieldname` char(20) NOT NULL default '$dfvalue';";
        $fields[1] = "char(20)";
    }
    else if($dtype == "float")
    {
        if($dfvalue == "" || preg_match("#[^0-9\.-]#", $dfvalue))
        {
            $dfvalue = 0;
        }
        $fields[0] = " `$fieldname` float NOT NULL default '$dfvalue';";
        $fields[1] = "float";
    }
    else if($dtype == "img" || $dtype == "media" || $dtype == "addon" || $dtype == "imgfile")
    {
        if(empty($dfvalue)) $dfvalue = '';
        if($mxlen=="") $mxlen = 200;
        if($mxlen > 255) $mxlen = 100;

        $fields[0] = " `$fieldname` varchar($mxlen) NOT NULL default '$dfvalue';";
        $fields[1] = "varchar($mxlen)";
    }
    else if($dtype == "multitext" || $dtype == "htmltext")
    {
        $fields[0] = " `$fieldname` mediumtext;";
        $fields[1] = "mediumtext";
    }
    else if($dtype=="textdata")
    {
        if(empty($dfvalue)) $dfvalue = '';

        $fields[0] = " `$fieldname` varchar(100) NOT NULL default '';";
        $fields[1] = "varchar(100)";
    }
    else if($dtype=="textchar")
    {
        if(empty($dfvalue)) $dfvalue = '';
        
        $fields[0] = " `$fieldname` char(100) NOT NULL default '$dfvalue';";
        $fields[1] = "char(100)";
    }
    else if($dtype=="checkbox")
    {
        $dfvalue = str_replace(',',"','",$dfvalue);
        $dfvalue = "'".$dfvalue."'";
        $fields[0] = " `$fieldname` SET($dfvalue) NULL;";
        $fields[1] = "SET($dfvalue)";
    }
    else if($dtype=="select" || $dtype=="radio")
    {
        $dfvalue = str_replace(',', "','", $dfvalue);
        $dfvalue = "'".$dfvalue."'";
        $fields[0] = " `$fieldname` enum($dfvalue) NULL;";
        $fields[1] = "enum($dfvalue)";
    }
    else
    {
        if(empty($dfvalue))
        {
            $dfvalue = '';
        }
        if(empty($mxlen))
        {
            $mxlen = 100;
        }
        if($mxlen > 255)
        {
            $mxlen = 250;
        }
        $fields[0] = " `$fieldname` varchar($mxlen) NOT NULL default '$dfvalue';";
        $fields[1] = "varchar($mxlen)";
    }
    return $fields;
}